import React, { FormEvent } from 'react';
import { Card, Form, Input, Button, message } from 'antd';
import axios from '../../common/axios';
import { useDispatch } from 'react-redux'
import Rules from '../../common/rules';

export default function Login() {
    const dispatch = useDispatch();
    const [form] = Form.useForm();
    const fnLogin = async (ev: FormEvent) => {
        ev.preventDefault();

        try {
            const values = await form.validateFields();
            console.log('Success:', values);

            let data = await axios({
                url: '/admin/login',
                method: 'post',
                data: values
            });
            console.log('Result', data)
            // const { token, token_expires, access } = data;

            dispatch({
                type: 'set_token',
                value: data
            })
            message.success('登录成功');
        } catch (errorInfo) {
            console.log(errorInfo);
        }
    }

    // let fnReg = ev => {
    //     ev.preventDefault();

    //     validateFields(async (err, values) => {
    //         if (!err) {
    //             // console.log('reg', values);
    //             try {
    //                 let { data } = await axios({
    //                     url: '/reg',
    //                     method: 'post',
    //                     data: values
    //                 });

    //                 console.log(data);
    //             } catch (e) {
    //                 console.log(e.response);
    //             }

    //         }
    //     });
    // };
    return (
        <Card title="登录" className="dialog">
            <Form form={form}>
                <Form.Item
                    name="username"
                    rules={[
                        { required: true, message: '用户名必须填写' },
                        { min: 4, message: '用户名最少4个字' },
                        { max: 32, message: '用户名最长32个字' },
                        { type: 'regexp', pattern: /^\w{4,32}$/, message: '用户名必须仅包含数字字母、下划线' }
                    ]}
                >
                    <Input type="text" placeholder="请输入用户名" />
                </Form.Item>
                <Form.Item
                    name="password"
                    rules={[
                        { required: true, message: '密码必须填写' },
                        { min: 6, message: '密码长度最少6' }
                    ]}
                >
                    <Input type="password" placeholder="请输入密码" />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" onClick={fnLogin}>登录</Button>
                    <Button type="default" onClick={() => {
                        // fnReg
                    }}>注册</Button>
                </Form.Item>
            </Form>
        </Card>
    )
}